package com.jietuo.class03;


/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2024/3/3
 * @description: 在一个数组中，一个数左边比它小的数的总和，叫数的小和，所有数的小和累加起来，叫数组小和。求数组小和。
 */
public class Code02_GetArrayLittleCount {

    public static void main(String[] args) {
        int[] arr = new int[]{1, 3, 4, 2, 5};
        int arrayLittleCount = process(arr, 0, arr.length - 1);
        System.out.println(arrayLittleCount);
    }

    private static int process(int[] arr, int left, int right) {
        if (left == right) {
            return 0;
        }
        int mid = left + ((right - left) >> 1);
        return process(arr, left, mid) + process(arr, mid + 1, right) + merge(arr, left, mid, right);
    }

    private static int merge(int[] arr, int left, int mid, int right) {
        int[] help = new int[right - left + 1];
        int helpIndex = 0;
        int leftIndex = left;
        int rightIndex = mid + 1;
        int littleCount = 0;
        while (leftIndex <= mid && rightIndex <= right) {
            littleCount += arr[leftIndex] < arr[rightIndex] ? (right - rightIndex + 1) * arr[leftIndex] : 0;
            help[helpIndex++] = arr[leftIndex] < arr[rightIndex] ? arr[leftIndex++] : arr[rightIndex++];
        }
        while (leftIndex <= mid) {
            help[helpIndex++] = arr[leftIndex++];
        }
        while (rightIndex <= right) {
            help[helpIndex++] = arr[rightIndex++];
        }
        for (int i = 0; i < help.length; i++) {
            arr[left + i] = help[i];
        }
        return littleCount;
    }
}
